from datetime import datetime, timedelta
from typing import List
from typing import Optional
import db.mysql as mq
import cache.global_cache as cache
import db.db as db
import jsl.getjslCookie as coo
import jsl.jslData as js
import myutil as mu
from db.connectmysql import global_db_cache  # 引入全局连接缓存实例
from entity.cbdata import CbData

# 全局唯一实例
global_cache = cache.GlobalCache()
jsl_cookie = "jsl_cookie"
base_dis_rate = "dis_rate"


# 拉取原始数据保存成csv
def save_data_csv(cb_data_list: List[CbData], csv_name_cn, csv_name_en):
    """

    @param cb_data_list:
    @param csv_name_cn:
    @param csv_name_en:
    @return:
    """
    # 1. 保存中文表头的CSV
    fetcher = js.BondDataJsl()
    if csv_name_cn is not None:
        fetcher.cb_data_mapper.save_to_csv_zh(cb_data_list, csv_name_cn, None)
        # 2. 生成字段说明文档（可选，方便查阅）
        fetcher.cb_data_mapper.generate_field_doc()
    if csv_name_en is not None:
        # 3. 生成英文的csv
        fetcher.cb_data_mapper.save_to_csv_en(cb_data_list, csv_name_en, None)


def get_discount_rate(conn, cursor, useday=None) -> float:
    """
    获取计算转债的贴现率 ,先从缓存里面获取,获取不到从数据库里面获取
    @param useday:
    @return:
    """
    if useday is None:
        # 获取当前日期
        today = datetime.now()
        # 计算昨天（当前日期减1天）
        yesterday = today - timedelta(days=1)
        # 格式化为YYYYMMDD字符串
        useday = yesterday.strftime('%Y%m%d')

    key = base_dis_rate + "_" + str(useday)
    dis_rate = global_cache.get(key)
    if dis_rate is None:
        print(f"缓存里面没有贴现率,从数据库获取")
        dis_rate = db.get_bond_rate_10(conn, cursor, useday)
        global_cache.set(key, dis_rate)
    return float(dis_rate)


# 计算可转债的纯债价值
def get_bond_value_jsl(year_left: float, dis_rate: float, rate_dic, expire_value: float) -> Optional[float]:
    """
    @param expire_value:
    @param year_left:  剩余年限
    @param dis_rate: 无风险利率
    @param useday: 计算时间
    @return: 纯债价值
    """
    bond_value = 0
    len_dic = len(rate_dic)
    temp_year_left = year_left - 1
    temp_len_dic = len_dic - 1
    while temp_year_left > 0 and temp_len_dic > 0:
        rate = rate_dic[temp_len_dic]
        # 计算当年的利息换算到现在是多少钱
        rate_money = rate / (1 + dis_rate / 100.0) ** (temp_year_left)  # 保留3位小数
        bond_value += rate_money
        temp_year_left -= 1
        temp_len_dic -= 1
    # 计算最后一年的本金现值
    benjin = expire_value / (1 + dis_rate / 100) ** (year_left)
    bond_value += benjin
    return round(bond_value, 2)


def get_expire_rt(driver, bond_id, price: float, year_left: float, ):
    """
    获取简化版到期收益率,不考虑贴现率
    @return:
    """
    cu_price = mu.get_data_by_selenium(driver, bond_id)
    ratio = (float(cu_price) - price) / year_left
    print("收益率", ratio)
    return ratio


if __name__ == "__main__":
    get_bond_value_jsl(2.589, 1.80, {1: 0.3, 2: 0.4, 3: 0.8, 4: 1.6, 5: 2.5, 6: 3.0}, 118.00)


def get_jsl_cookies() -> Optional[str]:
    """
    获取集思录cookie
    @return:
    """
    cookie = global_cache.get(jsl_cookie)
    if not cookie:
        jsl_cookie_fetcher = coo.GetJslCookie()
        cookie = jsl_cookie_fetcher.get_cookie()
        global_cache.set(jsl_cookie, cookie)
    return cookie


def get_cb_data_jsl() -> List[CbData]:
    """
    集思录获取可转债信息,当天,实时
    @param useday:
    @return:
    """
    cookie = get_jsl_cookies()
    fetcher = js.BondDataJsl()
    cb_data_list = fetcher.get_data(cookies=cookie)
    if cb_data_list is None or len(cb_data_list) == 0:
        # todo 通知获取可转债信息失败
        return None
    else:
        return cb_data_list


if __name__ == '__main__':
    conn = mq.get_meysql_conn()
    cursor = conn.cursor()
    get_discount_rate(conn, cursor, "20250930")
